package com.pctx.bibadevicemanager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pctx.bibacommon.result.Result;
import com.pctx.bibacommon.util.UuidUtil;
import com.pctx.bibadevicemanager.dao.DeviceUserMapper;
import com.pctx.bibadevicemanager.mfService.MfUserService;
import com.pctx.bibadevicemanager.pojo.DeviceInfo;
import com.pctx.bibadevicemanager.pojo.DeviceUser;
import com.pctx.bibadevicemanager.pojo.DeviceUserExample;
import com.pctx.bibadevicemanager.service.DeviceInfoService;
import com.pctx.bibadevicemanager.service.DeviceUserService;
import com.pctx.bibadevicemanager.service.TrackerSharePermissionService;
import com.pctx.bibadevicemanager.service.UserDeviceRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by chason on 2018/3/1.10:43
 */
@Service("deviceUserService")
public class DeviceUserServiceImpl implements DeviceUserService {
    @Autowired
    private DeviceUserMapper deviceUserMapper;
    @Autowired
    private UserDeviceRoleService userDeviceRoleService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private TrackerSharePermissionService trackerSharePermissionService;
    @Autowired
    private MfUserService mfUserService;

    @Override
    public boolean add(DeviceUser du) throws Exception {
        if (StringUtils.isEmpty(du.getUserUuid()))
            return false;

        // 判断是否已经关联
        DeviceUser old = getByDeviceUuidAndUserUuid(du.getDeviceUuid(), du.getUserUuid());
        if (null != old)
            return false;

        du.setUuid(UuidUtil.randomUUID());

        boolean flag = deviceUserMapper.insertSelective(du) > 0;
        if (!flag)
            return flag;

        // 添加设备用户-角色关联关系
        if (StringUtils.isNotEmpty(du.getRoleUuids())) {
            userDeviceRoleService.add(du.getUuid(), du.getRoleUuids());
        }

        return flag;
    }

    @Override
    public boolean update(DeviceUser du) throws Exception {
        if (StringUtils.isEmpty(du.getUuid()))
            return false;

        DeviceUser old = getByUuid(du.getUuid());
        if (null == old)
            return false;

        du.setId(old.getId());
        boolean flag = deviceUserMapper.updateByPrimaryKeySelective(du) > 0;

        if (!flag)
            return flag;

        // 删除旧的设备用户-角色关联关系
        userDeviceRoleService.delByUserDeviceUuid(du.getUuid());

        // 添加新的设备用户-角色关联关系
        if (StringUtils.isNotEmpty(du.getRoleUuids())) {
            userDeviceRoleService.add(du.getUuid(), du.getRoleUuids());
        }

        return flag;
    }

    @Override
    public DeviceUser getByUuid(String uuid) throws Exception {
        if (StringUtils.isEmpty(uuid))
            return null;

        DeviceUserExample example = new DeviceUserExample();
        DeviceUserExample.Criteria criteria = example.createCriteria();
        criteria.andUuidEqualTo(uuid);

        List<DeviceUser> list = deviceUserMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list))
            return null;

        return list.get(0);
    }

    @Override
    public List<DeviceUser> getByDeviceUuid(String deviceUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUuid))
            return null;

        DeviceUserExample example = new DeviceUserExample();
        DeviceUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceUuidEqualTo(deviceUuid);

        List<DeviceUser> list = deviceUserMapper.selectByExample(example);

        return list;
    }

    @Override
    public DeviceUser getByDeviceUuidAndUserUuid(String deviceUuid, String userUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUuid) || StringUtils.isEmpty(userUuid))
            return null;

        DeviceUserExample example = new DeviceUserExample();
        DeviceUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceUuidEqualTo(deviceUuid).andUserUuidEqualTo(userUuid).andStatusNotEqualTo(DeviceUser.STATUS_DEL);

        List<DeviceUser> list = deviceUserMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list))
            return null;

        return list.get(0);
    }

    /**
     * tracker 分享设备
     *
     * @param deviceUuid
     * @param userUuid
     * @return
     * @throws Exception
     */
    @Override
    public Result shareDevice(String deviceUuid, String userUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUuid) || StringUtils.isEmpty(userUuid))
            return Result.error("参数不能为空");

        DeviceInfo deviceInfo = deviceInfoService.getByUuid(deviceUuid);
        if (null == deviceInfo)
            return Result.error("设备不存在");

        DeviceUser deviceUser = getByDeviceUuidAndUserUuid(deviceUuid, userUuid);
        if (null != deviceUser)
            return Result.error("已经绑定过该设备");

        deviceUser = new DeviceUser();
        deviceUser.setUuid(UuidUtil.randomUUID());
        deviceUser.setDeviceUuid(deviceUuid);
        deviceUser.setUserUuid(userUuid);
        deviceUser.setType(DeviceUser.TYPE_SHARED);

        boolean flag = deviceUserMapper.insertSelective(deviceUser) > 0;
        if (!flag) {
            return Result.error("添加失败");
        }

        // 添加默认用户分享权限
        trackerSharePermissionService.addDefaultPermission(deviceUser.getUuid(), deviceUuid, userUuid);

        return Result.success("添加成功");
    }

    @Override
    public boolean add4Owner(String deviceUuid, String userUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUuid) || StringUtils.isEmpty(userUuid))
            return false;

        DeviceUser deviceUser = new DeviceUser();
        deviceUser.setUuid(UuidUtil.randomUUID());
        deviceUser.setDeviceUuid(deviceUuid);
        deviceUser.setUserUuid(userUuid);
        deviceUser.setType(DeviceUser.TYPE_OWNER);

        return deviceUserMapper.insert(deviceUser) > 0;
    }

    @Override
    public Result shareList(String deviceUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUuid))
            return Result.error("参数不能为空");

        List<Map> list = deviceUserMapper.shareList(deviceUuid);
        if (!CollectionUtils.isEmpty(list)) {
            for (Map map : list) {
                String userUuid = map.get("userUuid").toString();
                putUserInfoToMap(map, userUuid);
            }
        }
        return Result.success(list);
    }

    @Override
    public Result stopSahre(String deviceUserUuid) throws Exception {
        if (StringUtils.isEmpty(deviceUserUuid))
            return Result.error("参数不能为空");

        DeviceUser deviceUser = new DeviceUser();
        deviceUser.setUuid(deviceUserUuid);
        deviceUser.setStatus(DeviceUser.STATUS_DEL);

        boolean flag = updateByUuid(deviceUser);

        if (flag) {
            return Result.success("操作成功");
        } else {
            return Result.error("操作失败");
        }
    }

    private boolean updateByUuid(DeviceUser deviceUser) throws Exception {
        if (null == deviceUser || StringUtils.isEmpty(deviceUser.getUuid()))
            return false;

        DeviceUserExample example = new DeviceUserExample();
        DeviceUserExample.Criteria criteria = example.createCriteria();
        criteria.andUuidEqualTo(deviceUser.getUuid());

        return deviceUserMapper.updateByExampleSelective(deviceUser, example) > 0;
    }

    private Map putUserInfoToMap(Map map, String userUuid) {
        String userJsonStr = mfUserService.getByUuid(userUuid);
        JSONObject jsonObject = JSONObject.parseObject(userJsonStr);
        JSONObject userJson = jsonObject.getJSONObject("data");
        if (null != userJson) {
            map.put("username", userJson.getString("username"));
            map.put("mobile", userJson.getString("mobile"));
            map.put("headImgUrl",userJson.getString("headImgUrl"));
        }
        return map;
    }
}
